﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//子弹控制器，提供子弹动画控制、击中检测
public class BulletControlller : MonoBehaviour
{
    //游戏控制器
    GameController gameController;
    //子弹速度
    float bulletSpeed;
    //设计距离
    float shootDistance;
    //子弹动画机
    public Animator bulletAnimator;
    //动画速度
    float animationSpeed;
    //触发器
    public Collider2D bulletCollider;
    //弹孔预设
    public GameObject holePrefab;
    //自身Sprite渲染器
    public SpriteRenderer bulletSprite;
    //自身刚体
    Rigidbody2D bulletRigidbody2D;
    //风力
    Vector2 windForce;
    //击中音效
    public AudioSource hitAutio;

    // Start is called before the first frame update
    void Start()
    {
        //初始化对象及参数
        bulletRigidbody2D = GetComponent<Rigidbody2D>();
        gameController = GameObject.Find("GameController").GetComponent<GameController>();
        //仅在子弹发射时加载GameController中的射击参数，降低游戏复杂度
        bulletSpeed = gameController.getBulletSpeed();
        shootDistance = gameController.getShootDistance();
        bulletRigidbody2D.gravityScale = bulletRigidbody2D.gravityScale * gameController.getGravityCoefficient();
        windForce = new Vector2(gameController.getWindCoefficient(), 0);
        //子弹飞行时间
        float time = shootDistance / bulletSpeed;
        //动画速度（动画原始时长为1s，所以目标动画播放速度为原始速度的 1/time 倍。所以目标动画速度为 1/time *1 = 1/time ）
        animationSpeed = 1 / time;
    }

    // Update is called once per frame
    void Update()
    {
        //控制子弹动画速度
        AnimatorStateInfo animatorInfo = bulletAnimator.GetCurrentAnimatorStateInfo(0);
        if (animatorInfo.IsName("bulletFire"))
        {
            bulletAnimator.speed = animationSpeed;
        }
        //添加风力影响
        bulletRigidbody2D.AddForce(windForce);
    }

    //子弹击中回调（子弹动画播放完成时生成弹孔，并激活触发器）
    public void onHited() {
        //生成弹孔，锁定自身位置，移除Sprite渲染器，播放击中音效
        Instantiate(holePrefab, transform.position, transform.rotation);
        bulletRigidbody2D.constraints = RigidbodyConstraints2D.FreezePosition;
        bulletSprite.enabled = false;
        hitAutio.Play();
        //激活触发器
        bulletCollider.enabled = true;
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        //击中目标时提示
        if(other.name == "Target")
        {
            Debug.Log("击中：" + other.name);
        }
    }
}
